package com.chen.common.websocket.config;

import com.chen.base.utils.SpringContextHolder;
import com.chen.common.websocket.handler.WsSessionHandler;
import com.chen.common.websocket.interceptor.WebSocketInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistration;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Resource
    WsSessionHandler wsSessionHandler;

    @Override
    public void registerWebSocketHandlers(@NonNull WebSocketHandlerRegistry registry) {
        WebSocketHandlerRegistration registration = registry.addHandler(wsSessionHandler, "ws/comm")
                // 允许跨域访问
                .setAllowedOrigins("*").setAllowedOriginPatterns("*");

        // 配置拦截器
        Map<String, WebSocketInterceptor> interMap = SpringContextHolder.getAppContext().getBeansOfType(WebSocketInterceptor.class);
        if (!interMap.isEmpty()){
            WebSocketInterceptor[] interceptors = interMap.values().toArray(new WebSocketInterceptor[0]);
            registration.addInterceptors(interceptors);
        }
    }

    /**
     * 这个bean会自动注册使用了@ServerEndpoint注解声明的对象
     * 没有的话会报404
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
